layui.use(['table','layer','form', 'layedit','jquery'], function(){
    var table = layui.table
        ,layer = layui.layer
        ,form = layui.form
        ,layedit = layui.layedit
        ,$ = layui.jquery;

    var body = "";
    var checkStatus;//多选框选中状态
    var checkedData = "";
    //判断是否有选中行，没有得话则把修改按钮置灰
    $(function(){
        //获取到选中数据
        checkedData = layui.table.checkStatus('regList_table').data;
    });
    table.render({
        elem: '#regList_table'
        ,url:'../regimental/FindAlreadylPassRegimental.json'
        ,response: {
            statusName: 'code'
            ,statusCode: '100012'
            ,msgName: 'msg'
            ,countName: 'total'
            ,dataName: 'data'
        }
        ,toolbar: '#toolbar'
        ,title: '字典类型'
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{field:'regimental_id', title:'团长编号', fixed: 'left'}
            ,{field:'regimental_name', title:'团长名称', fixed: 'left'}
            ,{field:'regimental_phone', title:'手机号', fixed: 'left'}
            ,{field:'regimental_community', title:'社区名称', fixed: 'left'}
            ,{field:'detail_address', title:'具体地址', fixed: 'left'}
            ,{field:'regimental_statue', title:'团长状态', fixed: 'left',templet:"#statue"}
            ,{field:'createtime', title:'申请时间', templet : "<div>{{layui.util.toDateString(d.createtime, 'yyyy-MM-dd HH:mm:ss')}}</div>", fixed: 'left'}
            ,{fixed: 'right', title:'操作', toolbar: '#operations'
            }
        ]]
        ,page: true
        ,id: 'table'
        ,limit:15
        ,limits:[15,20,30,40]
        ,skin: 'line'
    });


    //打开弹出层表单
    function openForm(title,event,url1,url2,params){
        layer.open({
            type: 2,
            area:['70%', '50%'],
            fixed:true,
            anim: 2,
            offset: '20px',
            maxmin:false,
            scrollbar: false,
            title: title,
            content: ['/page/regimentaldetail.html','no'],
            end: function () {
                location.reload();
            },
            btn:['确认','取消'],
            success: function(layero, index) {
                //设置body为全局变量
                body = layer.getChildFrame('body',index);
                switch (event) {
                    case 'edit':
                        var regimentalId="";
                        $.each($.parseJSON(params),function (i,v) {
                            regimentalId=v.regimental_id;
                        })
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.getRegmentalInfo(regimentalId);
                        break;
                }
            },
            yes: function(index, layero){
                switch (event) {
                    case 'edit':
                        var regimentalId="";
                        $.each($.parseJSON(params),function (i,v) {
                            regimentalId=v.regimental_id;
                        });
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.updateRegimentalById(regimentalId);
                        break;
                }
            }
            ,btn2: function(index, layero){
                switch (event) {
                    case 'edit':
                        var regimentalId="";
                        var regimentalStatue="";
                        $.each($.parseJSON(params),function (i,v) {
                            regimentalId=v.regimentalId;
                            regimentalStatue = 3;
                        });
                        alert("你确定要驳回吗。。")
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.updateRegimental(regimentalId,regimentalStatue);
                        break;
                }
            }
        });
    }

    //删除选中行同时兼容多选和单选
    function delDicTypeByIds(url,idsStr){
        $.ajax({
            url:url,
            type:'post',
            async:true,
            data:{userId:idsStr},
            timeout:5000,    //超时时间
            dataType:'json', //返回的数据格式：json/xml/html/script/jsonp/text
            success:function(res){
                if(res.success){
                    layer.msg('用户删除成功！',{offset: '220px'});
                    //执行重载
                    table.reload('table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    }, 'data');
                }else
                {
                    layer.msg('用户删除失败！',{offset: '220px'});
                }
            },
            error:function(data){
                layer.msg('删除失败!',{offset: '220px'});
            }
        });
    }

    //头工具栏事件
    table.on('toolbar(regList_table)', function(obj){
        //设置选中状态为全局变量
        checkStatus = table.checkStatus(obj.config.id);
        /*  这两行报错有问题  var index = parent.layer.getFrameIndex(window.name);
            parent.layer.iframeAuto(index);*/
        switch(obj.event){
            case 'getCheckData':
                var data = checkStatus.data;
                layer.alert(JSON.stringify(data));
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：'+ data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选': '未全选');
                break;
            case 'addGoods':
                openForm('新增商品信息','addGoods','../dictionaryType/getMaxDIC_id.json','../dictionaryType/addDictionaryType.json',null);
                break;
            case 'delGoods':
                //获取要删除的行id
                var delData = checkStatus.data;
                if(delData.length>0)
                {
                    var delStr = "";
                    //解析要删除的数据
                    $.each(delData,function(index,value){
                        delStr+=value.id+',';
                    });
                    //进一步处理要删除的数据行的id
                    delStr = delStr.substring(0,delStr.length-1);
                    //询问是否要真的删除
                    layer.confirm('是否删除选中团长',{offset: '320px'}, function(index){
                        delWxGoodsById('../wxGoods/delWxGoodsById',delStr);
                        layer.close(index);
                    });
                }else
                {
                    layer.msg("请选择用户！",{offset: '220px'});
                }
                break;
        };
    });

    //监听行工具事件
    table.on('tool(regList_table)', function(obj){
        var data = obj.data;
        //console.log(obj)
        /*  var ids=data.id+',';
          alert(ids);*/
        if(obj.event === 'del'){
            layer.confirm('是否删除选中团长',{offset: '320px'}, function(index){
                DelRegimenttalById('../regimental/DelRegimenttalById.json',data.regimental_id);
                layer.close(index);
            });
        } else if(obj.event === 'edit'){
            var array=new Array();
            array.push(data);
            var params=JSON.stringify(array);
            openForm('修改商品信息','edit',null,null,params);
        }else if(obj.event==='statue')
        {
            var regimentalId=data.regimental_id;
            var regimentalStatue=data.regimental_statue;
            upStart(regimentalStatue,regimentalId);
        }
    });


    $("#mh_select").on('click',function () {
        mhSelect();
    });

    function mhSelect() {
        var goodsName = $('#mh').val();
        var goodsType=$("select[name='goodsType']").val();
        table.reload('table', {
            url: '../wxGoods/queryWxGoodsLimit'
            ,where: {
                goodsName : goodsName,
                goodsType : goodsType
            }
            ,page: {
                curr: 1
            }
        });
    }

    function upStart(regimentalStatue,regimentalId) {
        $.ajax({
            url:'../regimental/UpdateRegimenttalStatue.json',
            type:'post',
            async:true,
            data:{regimentalStatue:regimentalStatue,regimentalId:regimentalId},
            timeout:5000,    //超时时间
            // dataType:'json', //返回的数据格式：json/xml/html/script/jsonp/text
            success:function(res) {
                if(res>0)
                {
                    table.reload('table');
                }
            }
        });
    }

    function DelRegimenttalById(url,regimentalId){
        $.ajax({
            url:url,
            type:'post',
            async:true,
            data:{regimentalId:regimentalId},
            timeout:5000,    //超时时间
            dataType:'json', //返回的数据格式：json/xml/html/script/jsonp/text
            success:function(res){
                if(res>0){
                    layer.msg('团长删除成功！',{offset: '220px'});
                    //执行重载
                    table.reload('table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    }, 'data');
                }else
                {
                    layer.msg('用户删除失败！',{offset: '220px'});
                }
            },
            error:function(data){
                layer.msg('删除失败!',{offset: '220px'});
            }
        });
    }
});

